package top.mcwebsite.playandroid.business.tixi.impl.vm

import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import kotlinx.serialization.json.Json
import top.mcwebsite.playandroid.business.tixi.impl.api.TixiApiService
import top.mcwebsite.playandroid.common.network.api.NetworkService
import top.mcwebsite.playandroid.common.network.api.createApi
import top.mcwebsite.playandroid.common.network.model.ApiResult
import top.mcwebsite.playandroid.lib.mvi.base.BaseViewModel
import top.mcwebsite.playandroid.lib.mvi.model.Async
import top.mcwebsite.playandroid.lib.servicemanager.core.ServiceManager

class TixiViewModel : BaseViewModel<TixiIntent, TixiUiState, TixiUiEffect>(TixiUiState()) {

    private val tixiApiService: TixiApiService = ServiceManager.getService<NetworkService>().createApi()

    init {
        fetchTixiData()
    }

    private fun fetchTixiData() {
        setUiState {
            copy(tixiModels = Async.Loading)
        }
        viewModelScope.launch {
            when (val result = tixiApiService.tixiTree()) {
                is ApiResult.Success -> {
                    val tixiData = result.data.data
                    setUiState {
                        copy(tixiModels = Async.Success(tixiData ?: emptyList()))
                    }
                }
                is ApiResult.Failure -> {
                    setUiState {
                        copy(tixiModels = Async.Failed(result.cause.errorMsg, result.cause))
                    }
                }
            }
        }
    }

    override fun handleIntent(intent: TixiIntent) {
        when (intent) {
            is TixiIntent.OnTixiItemClickIntent -> {
                sendUiEffect(TixiUiEffect.GoArticleListUiEffect(intent.tixiModel))
            }
        }
    }
}